<template>
  <div :title="title" @back="() => $router.go(-1)">
    <a-spin :spinning="spinning">
      <div class="main">
        <a-form-model
          ref="formRef"
          :rules="rules"
          :model="form"
          layout="vertical"
        >
          <a-row>
            <a-col
              :span="8"
              class="main-col"
              style="border-right: 1px solid #eee;max-width:460px;"
            >
              <a-form-model-item :label="$t('all.autotext1277')" prop="flowName">
                <a-textarea
                  v-model="form.flowName"
                  :placeholder="$t('all.autotext817')"
                  :rows="3"
                  :maxLength="80"
                />
              </a-form-model-item>
              <a-form-model-item label="" class="check-all">
                <div>
                  <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">{{ $t('all.autotext562') }}</a-checkbox>
                </div>
              </a-form-model-item>
              <a-form-model-item :label="$t('all.autotext1153')" prop="researchIds">
                <a-checkbox-group
                  v-if="centerOptions.length > 0"
                  v-model="form.researchIds"
                  :options="centerOptions"
                  @change="onChange"
                />
                <a-empty style="margin-top: 50px;" v-else />
              </a-form-model-item>
            </a-col>
            <a-col :span="16" class="main-col">
              <a-form-model-item :label="$t('all.autotext277')" prop="flowNode">
                <div class="edit-wrap">
                  <div class="edit">
                    <div class="edit-normal">
                      <div class="normal-title">{{ $t('all.autotext246') }}</div>
                      <div class="normal-text">{{ $t('all.autotext1500') }}</div>
                    </div>
                    <addPop :index="0" @add="onAdd"></addPop>
                    <div v-for="(item, i) in form.flowNode" :key="i">
                      <div class="point-wrap">
                        <div class="point">
                          <div class="point-top">
                            <div class="point-title">{{ item.isMain ? $t('all.autotext62') : $t('all.autotext1461') }}</div>
                            <a-popconfirm
                              :title="$t('all.autotext631')"
                              :ok-text="$t('all.autotext792')"
                              :cancel-text="$t('all.autotext975')"
                              @confirm="delTap(i)"
                            >
                              <a-button icon="delete">{{ $t('all.autotext379') }}</a-button>
                            </a-popconfirm>
                          </div>
                          <div class="item-wrap">
                            <div class="item-top" v-if="!item.isMain">
                              <div class="item-title">{{ $t('all.autotext558') }}</div>
                              <a-select
                                class="item-select"
                                v-model="item.applyType"
                                mode="tags"
                                :placeholder="$t('all.autotext1057')"
                              >
                                <a-select-option v-for="j in expenseList" :value="j.applyType" :key="j.applyType">
                                  {{ j.applyType }}
                                </a-select-option>
                              </a-select>
                            </div>
                            <div class="item-top" v-for="(min, z) in item.person" :key="z">
                              <div class="item-flex">
                                <div class="item-title">{{ $t('all.autotext939') }}</div>
                                <a-checkbox class="item-check" :checked="min.type" @change="appointTap($event, i, z)">{{ $t('all.autotext742') }}</a-checkbox>
                              </div>
                              <a-select
                                class="item-select"
                                v-model="min.roleId"
                                mode="tags"
                                :placeholder="$t('all.autotext270')"
                              >
                                <a-select-option v-for="j in rolesList" :value="String(j.id)" :key="j.id">
                                  {{ j.name }}
                                </a-select-option>
                              </a-select>
                            </div>
                            <a-button
                              v-if="!item.isMain"
                              class="item-add"
                              type="link"
                              icon="plus"
                              @click="personAdd(i)"
                            >
                              {{ $t('all.autotext23') }}
                            </a-button>
                          </div>
                        </div>
                      </div>
                      <addPop :index="i+1" @add="onAdd"></addPop>
                    </div>
                    <div class="edit-normal">
                      <div class="normal-title">{{ $t('all.autotext62') }}</div>
                      <div class="normal-text">{{ $t('all.autotext1254') }}</div>
                    </div>
                  </div>
                </div>
              </a-form-model-item>
              <a-form-model-item :label="$t('all.autotext532')">
                <a-select
                  class="item-select"
                  v-model="form.ccForNew"
                  mode="tags"
                  :placeholder="$t('all.autotext270')"
                >
                  <a-select-option v-for="j in rolesList" :value="String(j.id)" :key="j.id">
                    {{ j.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <div class="btn-wrap">
                <a-space>
                  <a-button @click="cancel">{{ $t('all.autotext975') }}</a-button>
                  <a-button type="primary" @click="submit" :loading="loading">{{ $t('all.autotext49') }}</a-button>
                </a-space>
              </div>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-spin>
  </div>
</template>
<script>
import addPop from './components/addPop.vue'
import { approvalData } from './approvalData'
import { getList } from '@/api/overview/cost'
import { getRolesList, addApproval, insertLatestFlowInfoSnapshot, getUnusedResearchList, getFlowInfoById } from '@/api/overview/approval'
import cloneDeep from 'lodash.clonedeep'
export default {
  components: {
    addPop
  },
  data () {
    return {
      proId: '',
      spinning: false,
      title: this.$route.query.add ? (this.$route.query.type === '1' ? this.$t('all.autotext73.1') : this.$t('all.autotext73.2')) : (this.$route.query.type === '1' ? this.$t('all.autotext73.3') : this.$t('all.autotext73.4')),
      // 适用中心数据
      centerOptions: [],
      rolesList: [],
      expenseList: [],
      indeterminate: false, // 半全选状态样式
      checkAll: false, // 是否全选
      form: {
        id: '',
        flowName: '',
        researchIds: [],
        flowNode: [],
        ccForNew: []
      },
      rules: {
        flowName: [{ required: true, message: this.$t('all.autotext817'), trigger: 'change' }],
        researchIds: [{ type: 'array', required: true, message: this.$t('all.autotext727'), trigger: 'change' }],
        flowNode: [{ type: 'array', required: true, message: this.$t('all.autotext650'), trigger: 'change' }]
      },
      loading: false
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
    this.getUnusedResearchList()
    this.getRolesList()
    this.getExpenseList()
  },
  methods: {
    // 初始化数据
    async initData () {
      if (!this.$route.query.uid) return
      this.spinning = true
      const res = await getFlowInfoById({
        id: this.$route.query.uid,
        proId: this.proId,
        type: this.$route.query.type
      })
      this.spinning = false
      this.form.id = res.id
      this.form.flowName = res.flowName
      this.form.researchIds = res.researchIds.split(',')
      this.form.ccForNew = res.ccForNew ? res.ccForNew.split(',') : []
      const editRoles = []
      this.form.flowNode = []
      if (res.nodeList && res.nodeList.length) {
        let approverList = cloneDeep(res.nodeList)
        approverList = approverList.filter(v => v.nodeType !== 2)
        approverList.forEach(item => {
          item.isMain = !item.parentCode
          if (item.isMain) {
            item.person = [{
              type: item.type === 1,
              roleId: item.roleId ? item.roleId.split(',') : []
            }]
          } else {
            let person = JSON.parse(item.conditionValueStr)
            item.person = person.map(p => {
              return {
                type: p.type,
                roleId: p.roleId.split(',')
              }
            })
          }
          item.applyType = item.applyType ? item.applyType.split(',') : []
          this.form.flowNode.push(item)
        })
        // 删除最后一条数据
        // this.form.flowNode.pop()
        this.form.flowNode.forEach(item => {
          if (editRoles.indexOf(item.roleId) === -1) {
            editRoles.push(item.roleId)
          }
        })
        const ccCopy = res.ccForNew ? res.ccForNew.split(',') : []
        ccCopy.forEach(item => {
          if (editRoles.indexOf(item.roleId) === -1) {
            editRoles.push(item.roleId)
          }
        })
      }
      // 适用中心反显
      let list = res.researchList.map(item => {
        return {
          value: item.id,
          label: item.researchCenterNo + ' - ' + item.orgName
        }
      })
      this.centerOptions = [...list, ...this.centerOptions]
      this.form.researchIds = list.map(item => item.value)
      this.indeterminate = true
    },
    async getUnusedResearchList () {
      const res = await getUnusedResearchList({
        proId: this.proId,
        type: this.$route.query.type
      })
      this.centerOptions = res.map(item => {
        return {
          value: item.id,
          label: item.researchCenterNo + ' - ' + item.orgName
        }
      })
      this.initData()
    },
    async getRolesList () {
      const res = await getRolesList({ proId: this.proId })
      this.rolesList = res
    },
    async getExpenseList () {
      const res = await getList({
        proId: this.proId,
        pageSize: 99,
        pageNumber: 1,
        type: this.$route.query.type,
        status: 1
      })
      // this.expenseList = res.content.filter(v => v.defaulted)
      this.expenseList = res.content
    },
    /**
     * 适用中心选择
     */
    onChange (checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.centerOptions.length
      this.checkAll = checkedList.length === this.centerOptions.length
    },
    /**
     * 全选
     */
    onCheckAllChange (e) {
      const arr = this.centerOptions.map(item => item.value)
      this.form.researchIds = e.target.checked ? arr : []
      this.indeterminate = false
      this.checkAll = e.target.checked
    },
    /**
     * 添加流程节点
     */
    onAdd (type, index) {
      if (type === 1) {
        this.form.flowNode.splice(index, 0, {
          isMain: true,
          person: [
            {
              type: false,
              roleId: []
            }
          ]
        })
      } else {
        this.form.flowNode.splice(index, 0, {
          isMain: false,
          person: [
            {
              type: false,
              roleId: []
            }
          ],
          applyType: []
        })
      }
    },
    /**
     * 删除节点
     */
    delTap (i) {
      this.form.flowNode.splice(i, 1)
    },
    /**
     * 是否指定用户
     */
    appointTap (e, i, z) {
      this.form.flowNode[i].person[z].type = e.target.checked
    },
    /**
     * 添加审批人
     */
    personAdd (i) {
      this.form.flowNode[i].person.push({
        type: false,
        roleId: []
      })
    },
    /**
     * 提交
     */
    submit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.form.flowNode.some(v => {
            return v.person.some(i => i.roleId.length === 0)
          })) {
            this.$message.error(this.$t('all.autotext253'))
            return
          }
          if (this.form.flowNode.some(v => !v.isMain && v.applyType.length === 0)) {
            this.$message.error(this.$t('all.autotext185'))
            return
          }
          this.addApproval()
        }
      })
    },
    cancel () {
      this.$router.back()
    },
    // 发起添加请求 走新增/编辑接口
    addApproval () {
      this.loading = true
      const params = {
        id: this.form.id || null,
        proId: this.proId,
        type: this.$route.query.type,
        flowName: this.form.flowName,
        ccForNew: this.form.ccForNew.join(','),
        researchIds: this.form.researchIds.join(','),
        flowNode: JSON.stringify(approvalData(this.form.flowNode))
      }
      if (this.$route.query.add) {
        addApproval(params)
          .then(res => {
            this.$message.success(this.$t('all.autotext344'))
            this.loading = false
            this.$router.back()
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        insertLatestFlowInfoSnapshot(params)
          .then(res => {
            this.$message.success(this.$t('all.autotext344'))
            this.loading = false
            this.$router.back()
          })
          .catch(() => {
            this.loading = false
          })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.main {
  background: #fff;
  padding: 20px 0;
  /deep/.main-col {
    padding: 0 20px;
    .check-all {
      position: absolute;
      right:20px;
    }
    .ant-checkbox-group {
      width: 100%;
    }
    .ant-checkbox-group-item {
      display: flex;
      align-items: flex-end;
      width:100%;
      padding: 18px 20px;
      border: 1px solid #E9EAEC;
      border-radius: 4px;
      margin-bottom: 12px;
      overflow: hidden;
      span {
        display: block;
      }
      .ant-checkbox + span {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .edit-wrap {
    background: #F4F5F7;
    padding: 24px 34px;
    position: relative;
    .edit-normal {
      padding: 8px 24px;
      border-left: 1px solid #CED0D6;
      .normal-title {
        color: #031F47;
        font-size: 16px;
      }
      .normal-text {
        color: #687991;

      }
    }
  }
  .point-wrap {
    padding: 0 0 0 26px;
    border-left: 1px solid #CED0D6;
    padding-bottom: 20px;
    .point {
      background: #fff;
      .point-top {
        padding: 20px 16px;
        border-bottom: 1px solid #CED0D6;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .point-title {
          font-size: 20px;
          color: #031F47;
        }
      }
      .item-wrap {
        padding-bottom: 24px;
      }
      .item-top {
        padding: 24px 20px 0;
        .item-flex {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .item-check {
          color: #687991;
        }
        /deep/.item-select {
          margin-top: 12px;
        }
        .item-add {
          padding: 0;
        }
      }
    }
  }
  .btn-wrap {
    text-align: right;
  }
}
</style>
